from twisted.internet import reactor, protocol, endpoints
from twisted.protocols import basic


class PubSubDemo(basic.LineReceiver):
    def __init__(self, factory):
        self.factory = factory

    def connectionMade(self):
        self.factory.clients.add(self)

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def lineReceived(self, line):
        for c in self.factory.clients:
            source = u"<{}> ".format(self.transport.getHost()).encode("ascii")
            c.sendLine(source + line)


class PubFactory(protocol.Factory):
    def __init__(self):
        self.clients = set()

    def buildProtocol(self, addr):
        return PubSubDemo(self)


def _test_pubsub():
    """
    # TODO 未验证
    _test_pubsub()
    >
    Telnet 192.168.1.103 8000
    Telnet 192.168.1.103 8000
    """
    endpoints.serverFromString(reactor, "tcp:8000:interface=0.0.0.0").listen(PubFactory())
    reactor.run()


if __name__ == '__main__':
    _test_pubsub()
